package com.example.student.controller;

import com.example.student.config.BizException;
import com.example.student.entity.FileInfo;
import com.example.student.entity.Student;
import com.example.student.service.FileInfoService;
import com.example.student.service.StudentService;
import com.example.student.utils.FileUtils;
import com.example.student.utils.ResultBody;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("file")
public class FileInfoController {

    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private StudentService studentService;


    /**
     * 文件上传
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public ResultBody batchUpload(HttpServletRequest request) {
         // 从Request域中获取多文件
        Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
        List<FileInfo> fileInfos = fileInfoService.saveFiles(fileMap);
        return ResultBody.success(fileInfos);
    }

    /**
     * 文件导入
     * @param request
     * @return
     */
    @PostMapping("/import")
    public ResultBody importStudent(HttpServletRequest request) {
        // 从Request域中获取多文件
        Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
        List<FileInfo> fileInfos = fileInfoService.saveFiles(fileMap);
        try{
            FileInputStream fileIn = new FileInputStream(fileInfos.get(0).getFilePath());
            //根据指定的文件输入流导入Excel从而产生Workbook对象
            Workbook wb0 = new HSSFWorkbook(fileIn);
            //获取Excel文档中的第一个表单
            Sheet sht0 = wb0.getSheetAt(0);
            for(int i = 1;i<sht0.getPhysicalNumberOfRows();i++){
                Student student = new Student();
                student.setNum(String.valueOf(sht0.getRow(i).getCell(0).getStringCellValue()));
                student.setName(sht0.getRow(i).getCell(1).getStringCellValue());
                student.setSex(sht0.getRow(i).getCell(2).getStringCellValue());
                student.setFaculty(sht0.getRow(i).getCell(3).getStringCellValue());
                student.setGrades(sht0.getRow(i).getCell(4).getStringCellValue());
                student.setMajor(sht0.getRow(i).getCell(5).getStringCellValue());
                student.setStatus(1);
                studentService.add(student);
            }
        }catch (Exception e){
            throw new BizException(e.getMessage());
        }
        return ResultBody.success("");
    }

    /**
     * 文件下载
     * @param request
     * @param response
     * @param id
     */
    @GetMapping("/download")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response,String id) {
        FileInfo fileInfo = fileInfoService.getById(id);
        if (fileInfo == null) {
            throw new BizException("失败!文件未找到!");
        }
        String fileName = fileInfo.getOriginalName();
        if (fileName != null) {
            File file = new File(fileInfo.getFilePath());
            if (file.exists()) {
                // 设置下载响应头
                FileUtils.setHeader(request,response,fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (IOException e) {
                    throw new BizException("下载文件时出现异常! 错误信息:" + e.getMessage());
                } finally {
                    try {
                        bis.close();
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 图片在线预览
     * @param response
     * @param id
     */
    @GetMapping("/img/{id}")
    public void getImg(HttpServletResponse response, @PathVariable("id") String id) {
        FileInfo fileInfo = fileInfoService.getById(id);
        String imgTyps = ".jpg.jpeg.gif.png.bmp";
        if(!imgTyps.contains(fileInfo.getFileType().toLowerCase())){
            throw new BizException("不支持的文件格式!");
        }
        String type = fileInfo.getFileType().replace(".", "/");
        response.setContentType("image" + type);
        File file = new File(fileInfo.getFilePath());
        if (file.exists()) {
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (IOException e) {
                throw new BizException("获取图片异常! 错误信息:" + e.getMessage());
            } finally {
                try {
                    assert bis != null;
                    bis.close();
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
